package com.amos.stuff.proxyandspring.biz.util;

import com.alibaba.fastjson.JSONObject;
import com.amos.stuff.proxyandspring.biz.CustomerPropertiesHandler;
import com.amos.stuff.proxyandspring.biz.type.CustomerPropertiesTypeEnum;
import com.amos.stuff.util.SpringContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Project: stuff
 * @ClassName: CustomPropertiesTypeBeanInitialization
 * @Package: com.amos.stuff.proxyandspring.biz.util
 * @author: zhuqb
 * @Description: 自定义属性处理器和自定义属性类型数据初始化
 * <p>
 * 通过自定义属性处理接口来获取所有的自定义属性处理器
 * 组装每个自定义属性处理器对应的类型
 * <p>
 * 以Map结构来存储
 * <p>
 * 这里之所以使用枚举对象是为了解决hash冲突的现象
 * @date: 2019/9/26 0026 下午 16:07
 * @Version: V1.0
 */
public class CustomPropertiesTypeBeanInitialization {
    private final static Logger logger = LoggerFactory.getLogger(CustomPropertiesTypeBeanInitialization.class);

    /**
     * 首先获取
     *
     * @return
     */
    public static Map<CustomerPropertiesTypeEnum, CustomerPropertiesHandler> getMap() {
        logger.info("init...");

        Map<CustomerPropertiesTypeEnum, CustomerPropertiesHandler> map
                = new HashMap<>(CustomerPropertiesTypeEnum.values().length);

        // 首先获取 CustomerPropertiesHandler 接口的所有的实现类
        Map<String, CustomerPropertiesHandler> clazzes = SpringContext.getApplicationContext().getBeansOfType(CustomerPropertiesHandler.class);

        for (Map.Entry<String, CustomerPropertiesHandler> entry : clazzes.entrySet()) {

            logger.info("解析到的class文件：{}", entry.getValue().getClass());
            CustomerPropertiesHandler handler = SpringContext.getBean(entry.getValue().getClass());
            map.put(handler.type(), handler);
        }
        logger.info("解析后的customPropertiesMap:{}", JSONObject.toJSONString(map));
        return map;
    }
}
